package dao;

import model.User;
import org.apache.commons.dbutils.DbUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import utils.DataSourceUtils;

import javax.management.Query;
import java.sql.SQLException;

public class UserDao {


    public void addUser(User user) throws SQLException {
        //        拿到执行者对象
        QueryRunner r = new QueryRunner(DataSourceUtils.getDataSource());
        String sql = "insert into user(username,email,password," +
                "name, phone,address,isadmin,isvalidate)" +
                "values(?,?,?,?,?,?,?,?)";
        //        sql
        r.update(sql, user.getUsername(), user.getEmail(), user.getPassword(), user.getName()
                , user.getPhone(), user.getAddress(), user.isIsadmin(), user.isIsvalidate());
    }
//    执行

    //判断username是否存在
    public boolean isUsernameExist(String username) throws SQLException {
//        拿到执行者对象
        QueryRunner r = new QueryRunner(DataSourceUtils.getDataSource());
//        sql
        String sql = "select * from user where username=?";
//        执行
        User user = r.query(sql, new BeanHandler<User>(User.class), username);
        if (user == null) {
            return false;
        } else {
            return true;
        }
    }

    //判断email是否存在
    public boolean isEmailExist(String email) throws SQLException {

//        拿到执行者对象
        QueryRunner r = new QueryRunner(DataSourceUtils.getDataSource());
//        sql
        String sql = "select * from user where email=?";
//        执行
        User user = r.query(sql, new BeanHandler<User>(User.class), email);

        if (user == null) {
            return false;
        } else {
            return true;
        }
    }


    //    username password 查询
    public User selectUsernamePassword(String username, String password) throws SQLException {
//       拿到执行者对象
        QueryRunner r = new QueryRunner(DataSourceUtils.getDataSource());
//                sql
        String sql = "select* from user where username= ? and password = ?";
//          执行sql
        return r.query(sql, new BeanHandler<User>(User.class), username, password);

    }

    //email password 查询
    public User selectEmailPassword(String email, String password) throws SQLException {
//       拿到执行者对象
        QueryRunner r = new QueryRunner(DataSourceUtils.getDataSource());
//                sql
        String sql = "select* from user where email= ? and password = ?";
//          执行sql
        return r.query(sql, new BeanHandler<User>(User.class), email, password);

    }


}

